package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: 杰
 * @date: 2024/1/17 16:03
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        String respJson = "";
        if (blogId == null) {
            //请求的是博客列表页
            List<Blog> list = blogDao.getBlogs();
            respJson = objectMapper.writeValueAsString(list);
        } else {
            //请求的是博客页
            Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
            System.out.println(blogId);
            System.out.println(blog);
            respJson = objectMapper.writeValueAsString(blog);
        }
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || content == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("内容或标题为空");
            return;
        }
        //获取当前会话中的对象
        HttpSession session = req.getSession(false);
        User user = (User) session.getAttribute("user");
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUid());
        BlogDao blogDao = new BlogDao();
        try {
            blogDao.insert(blog);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.sendRedirect("blog_list.html");
    }
}
